package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @description:
 * @author: Limingjie
 * @date: 2020/10/28-5:53 PM
 * @Version: 1.0.0
 */
@RestController
@RequestMapping("/menu")
@Slf4j
public class MenuController {


    @Reference
    private MenuService menuService;

    //菜单编辑
    @RequestMapping("/menuEdit")
    public Result edit(@RequestBody Menu menu) {
        log.debug("menuEdit:" + menu);
        menuService.edit(menu);
        log.debug("菜单修改成功");
        return new Result(true, MessageConst.EDIT_MENU_SUCCESS);
    }

    //菜单编辑根据id回显数据
    @RequestMapping("/menuEditById")
    public Result menuEditById(Integer id) {
        log.debug("menuEditById:" + id);
        Menu menu = menuService.editById(id);
        log.debug("根据id查询菜单成功");
        return new Result(true, MessageConst.QUERY_MENU_SUCCESS, menu);
    }

    //根据id删除菜单
    @RequestMapping("/menuDeleteById")
    public Result menuDeleteById(Integer id) {
        log.debug("menuDeleteById:" + id);
        menuService.deleteById(id);
        log.debug("根据id删除菜单成功");
        return new Result(true, MessageConst.DELETE_MENU_SUCCESS);
    }

    @RequestMapping("/findMenuPage")
    public Result findMenuPage(@RequestBody QueryPageBean queryPageBean) {
        log.debug("controller:" + queryPageBean);
        PageResult pageResult = menuService.findMenuPage(queryPageBean);
        log.debug("PageResult:" + pageResult);
        return new Result(true, MessageConst.QUERY_MENULIST_SUCCESS, pageResult);
    }

    @RequestMapping("/menuAdd")
    public Result menuAdd(Integer level, @RequestBody Menu menu) {

        log.debug("controller:" + menu);

        //判断表单是否为空
        if (menu == null) {
            return new Result(false, MessageConst.ADD_MENU_FAIL);
        }

        //如果数据库中没有当前添加的菜单项，判断菜单等级
        //获取最高级路径id
        //List<Integer> parentMenuId = menuService.findParentMenuId();

        //获取到路径中最大的值
        //Integer maxMenuPath = menuService.findMaxPath(level);

        //如果为1级菜单
        if (level == 1) {
            //如果菜单等级设为1，说明前端页面要添加一个新的父菜单
            //判断数据库中是否存在此path
            long count = menuService.findWhetherExists(menu.getPath());
            if (count > 0) {
                //如果count大于0，说明数据库中有该父类菜单
                return new Result(false, MessageConst.MENU_ALREADY_EXIST);
            }
            //否则说明数据库中没有该新增父菜单,可以向数据中添加当前父菜单
            //查询表中最大优先级的值
            Integer maxPriority = menuService.findMaxPriority(level);
            //添加优先级，获取之后做+1操作
            menu.setPriority(maxPriority + 1);
            menuService.add(menu, level);
            log.debug("新增父菜单成功");
            return new Result(true, MessageConst.ADD_MENU_SUCCESS);
        } else if (level == 2) {
            //为2级菜单,说明前端页面需要添加二级路径
            //获取输入的路径
            String menuPath = menu.getPath();
            String[] pathStr = menuPath.split("/");
            String[] split = pathStr[1].split("-");
            String parentMenuId = split[0];
            String sonMenuId = split[1];
            //拿到前端输入的路径后，判断父路径值和子路径值
            //整体判断路径是否存在
            long count = menuService.findWhetherExists(menuPath);
            if (count > 0) {
                //存在
                return new Result(false, MessageConst.MENU_ALREADY_EXIST);
            }
            //不存在,获取优先级最大的路径的值
            String path = menuService.findMaxPriorityByCondition(level, parentMenuId);
            String[] queryPathStr = path.split("/");
            String[] queryPath = queryPathStr[1].split("-");
            String queryPathSon = queryPath[1];
            sonMenuId = String.valueOf(Integer.parseInt(queryPathSon) + 1);
            //拼接二级路径
            String joinPath = "/" + parentMenuId + "-" + sonMenuId;
            menu.setPath(joinPath);
            // 给路径优先级赋值
            //查询表中最大优先级的值
            Integer maxPriority = menuService.findMaxPriority(level);
            menu.setPriority(maxPriority + 1);

            //拿到父级路径的id
            Integer parentId = menuService.findParentId(parentMenuId);

            //将父级路径id赋值给parentMenuId
            menu.setParentMenuId(parentId);
            menuService.add(menu, level);
            log.debug("新增多级菜单成功");
            return new Result(true, MessageConst.ADD_MENU_SUCCESS);

        } else {
            return new Result(false, MessageConst.MENU_LEVEL_REINPUT);
        }
    }

    @RequestMapping("/findAll")
    public Result findAll() {
        log.debug("查询所有的菜单");
        List<Menu> menuList = menuService.findAll();

        log.debug("查询所有的菜单：" + menuList);

        return new Result(true, MessageConst.ACTION_SUCCESS, menuList);
    }

    @RequestMapping("/getMenuList")
    public Result getMenuList(HttpSession session) {
        session.getAttribute("SPRING_SECURITY_CONTEXT");
        session.getAttributeNames(); //可以获取session中所有的参数名
        //SecurityContextHolder 帮助类， 可以直接获取 session中 securityContext对象
        // SecurityContext: 上下文对象, 包含了用户信息和权限信息
        SecurityContext context = SecurityContextHolder.getContext();
        //获取认证对象
        Authentication authentication = context.getAuthentication();
        //获取principal 对象
        Object principal = authentication.getPrincipal();
        //如果 没有登录，获取到的是匿名用户，如果的登录了获取到的User对象
        //instanceof : 实例类型判断运算符
        String username = null;
        if(principal instanceof User){
            User u = (User) principal;
            username = u.getUsername();
        }
        log.debug("获取到的用户名为：" + username);
        Result result =menuService.getMenuList(username);
        return result;
    }


}